import { defineStore } from 'pinia'
import i18n from '@/language'
import type {
  Theme,
  ThemeColors,
  ThemeColorKey,
  PreferencesState,
  Language
} from './types'
import {
  PREFERENCES_KEY,
  basePreferences,
  getSystemTheme,
  startThemeChangeListener,
  stopThemeChangeListener,
  getBrowserLanguage
} from './utils'

export const usePreferencesStore = defineStore('preferences', {
  state: (): PreferencesState => JSON.parse(JSON.stringify(basePreferences)),
  getters: {
    isDark: (state) => state.appearance.theme.currentTheme === 'dark'
  },
  actions: {
    setTheme(theme: Theme) {
      this.appearance.theme.theme = theme
      if (theme === 'system') {
        this.appearance.theme.currentTheme = getSystemTheme()
        startThemeChangeListener()
      } else {
        this.appearance.theme.currentTheme = theme
        stopThemeChangeListener()
      }
      const flag = this.appearance.theme.currentTheme === 'dark'
      document.documentElement.classList.toggle('dark', flag)
    },
    setThemeColors(colors: ThemeColors) {
      this.appearance.theme.themeColors = colors
      for (const key in this.appearance.theme.themeColors) {
        const colorKey = `--core-${key}-color`
        const colors = this.appearance.theme.themeColors
        const value = colors[key as ThemeColorKey]
        document.documentElement.style.setProperty(colorKey, value)
      }
    },

    setLanguage(language: Language) {
      this.general.lang.language = language
      if (language === 'auto') {
        this.general.lang.currentLangeuage = getBrowserLanguage()
      } else {
        this.general.lang.currentLangeuage = language
      }
      i18n.global.locale.value = this.general.lang.currentLangeuage
    },

    initPreferences() {
      const data = localStorage.getItem(PREFERENCES_KEY)
      if (data) {
        this.$state = JSON.parse(data)
        this.setLanguage(this.general.lang.language)
        this.setTheme(this.appearance.theme.theme)
        this.setThemeColors(this.appearance.theme.themeColors)
      }
    },

    resetPreferences() {
      localStorage.setItem(PREFERENCES_KEY, JSON.stringify(basePreferences))
      this.initPreferences()
    }
  }
})
